package com.visual.api.rest;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigInteger;

import com.visual.api.dto.BladeVisualDTO;
import com.visual.api.mapping.BladeVisualConfigMapping;
import com.visual.api.mapping.BladeVisualMapping;
import com.visual.core.domain.BladeVisual;
import com.visual.core.domain.BladeVisualConfig;
import com.visual.core.domain.BladeVisualMap;
import com.visual.core.filter.BladeVisualSearchContext;
import com.visual.core.http.ResponseWrapper;
import com.visual.core.service.IBladeVisualConfigService;
import com.visual.core.service.IBladeVisualService;
import com.visual.util.annotation.VersionCheck;
import liquibase.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Api(tags = {"可视化表列表" })
@RestController("api-bladevisual")
@RequestMapping("")
public class BladeVisualResource {

    @Autowired
    public IBladeVisualService bladevisualService;

    @Autowired
    @Lazy
    public BladeVisualMapping bladevisualMapping;

    @Autowired
    public IBladeVisualConfigService bladevisualconfigService;

    @Autowired
    @Lazy
    public BladeVisualConfigMapping bladevisualconfigMapping;

    @Value("${file.path}")
    private String FILE_PATH;

    @ApiOperation(value = "新建可视化表", tags = {"可视化表" },  notes = "新建可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals")
    public ResponseEntity<BladeVisualDTO> create(@Validated @RequestBody BladeVisualDTO bladevisualdto) {
        BladeVisual domain = bladevisualMapping.toDomain(bladevisualdto);
		bladevisualService.create(domain);
        BladeVisualDTO dto = bladevisualMapping.toDto(domain);
        BladeVisualConfig config = new BladeVisualConfig();
        config.setId(domain.getId());
        config.setVisualid(domain.getId());
        config.setDetail(bladevisualdto.getDetail());
        config.setComponent(bladevisualdto.getComponent());
        bladevisualconfigService.create(config);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "批量新建可视化表", tags = {"可视化表" },  notes = "批量新建可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<BladeVisualDTO> bladevisualdtos) {
        bladevisualService.createBatch(bladevisualMapping.toDomain(bladevisualdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "bladevisual" , versionfield = "updatetime")
    @ApiOperation(value = "更新可视化表", tags = {"可视化表" },  notes = "更新可视化表")
	@RequestMapping(method = RequestMethod.PUT, value = "/bladevisuals/{bladevisual_id}")
    public ResponseEntity<BladeVisualDTO> update(@PathVariable("bladevisual_id") Long bladevisual_id, @RequestBody BladeVisualDTO bladevisualdto) {
		BladeVisual domain  = bladevisualMapping.toDomain(bladevisualdto);
        domain.setId(bladevisual_id);
		bladevisualService.update(domain );
		BladeVisualDTO dto = bladevisualMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "批量更新可视化表", tags = {"可视化表" },  notes = "批量更新可视化表")
	@RequestMapping(method = RequestMethod.PUT, value = "/bladevisuals/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<BladeVisualDTO> bladevisualdtos) {
        bladevisualService.updateBatch(bladevisualMapping.toDomain(bladevisualdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "删除可视化表", tags = {"可视化表" },  notes = "删除可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals/remove")
    public ResponseEntity<Boolean> remove(@RequestBody Map<String, Object> params) {
        Long bladevisual_id = Long.valueOf(params.get("ids").toString());
        return ResponseEntity.status(HttpStatus.OK).body(bladevisualService.remove(bladevisual_id));
    }

    @ApiOperation(value = "批量删除可视化表", tags = {"可视化表" },  notes = "批量删除可视化表")
	@RequestMapping(method = RequestMethod.DELETE, value = "/bladevisuals/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<Long> ids) {
        bladevisualService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @ApiOperation(value = "获取可视化表", tags = {"可视化表" },  notes = "获取可视化表")
	@RequestMapping(method = RequestMethod.GET, value = "/bladevisuals/{bladevisual_id}")
    public ResponseEntity<ResponseWrapper<Map<String,Object>>> get(@PathVariable("bladevisual_id") Long bladevisual_id) {
        BladeVisual domain = bladevisualService.get(bladevisual_id);
        BladeVisualConfig config = bladevisualconfigService.get(bladevisual_id);

        Map<String,Object> data = new HashMap<>();
        data.put("visual", bladevisualMapping.toDto(domain));
        data.put("config", bladevisualconfigMapping.toDto(config));

        ResponseWrapper<Map<String,Object>> responseWrapper = new ResponseWrapper<>();
        responseWrapper.setSuccess(true);
        responseWrapper.setData(data);
        return ResponseEntity.status(HttpStatus.OK).body(responseWrapper);
    }

    @ApiOperation(value = "获取可视化表草稿", tags = {"可视化表" },  notes = "获取可视化表草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/bladevisuals/getdraft")
    public ResponseEntity<BladeVisualDTO> getDraft(BladeVisualDTO dto) {
        BladeVisual domain = bladevisualMapping.toDomain(dto);
        return ResponseEntity.status(HttpStatus.OK).body(bladevisualMapping.toDto(bladevisualService.getDraft(domain)));
    }

    @ApiOperation(value = "检查可视化表", tags = {"可视化表" },  notes = "检查可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody BladeVisualDTO bladevisualdto) {
        return  ResponseEntity.status(HttpStatus.OK).body(bladevisualService.checkKey(bladevisualMapping.toDomain(bladevisualdto)));
    }

    @ApiOperation(value = "保存可视化表", tags = {"可视化表" },  notes = "保存可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals/save")
    public ResponseEntity<BladeVisualDTO> save(@RequestBody BladeVisualDTO bladevisualdto) {
        BladeVisual domain = bladevisualMapping.toDomain(bladevisualdto);
        bladevisualService.save(domain);
        return ResponseEntity.status(HttpStatus.OK).body(bladevisualMapping.toDto(domain));
    }

    @ApiOperation(value = "批量保存可视化表", tags = {"可视化表" },  notes = "批量保存可视化表")
	@RequestMapping(method = RequestMethod.POST, value = "/bladevisuals/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<BladeVisualDTO> bladevisualdtos) {
        bladevisualService.saveBatch(bladevisualMapping.toDomain(bladevisualdtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

	@ApiOperation(value = "获取数据集", tags = {"可视化表" } ,notes = "获取数据集")
    @RequestMapping(method= RequestMethod.GET , value="/bladevisuals/fetchdefault")
	public ResponseEntity<List<BladeVisualDTO>> fetchDefault(BladeVisualSearchContext context) {
        Page<BladeVisual> domains = bladevisualService.searchDefault(context) ;
        List<BladeVisualDTO> list = bladevisualMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

	@ApiOperation(value = "查询数据集", tags = {"可视化表" } ,notes = "查询数据集")
    @RequestMapping(method= RequestMethod.POST , value="/bladevisuals/searchdefault")
	public ResponseEntity<Page<BladeVisualDTO>> searchDefault(@RequestBody BladeVisualSearchContext context) {
        Page<BladeVisual> domains = bladevisualService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(bladevisualMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}


    @ApiOperation(value = "保存文件", tags = {"可视化表" } ,notes = "保存文件")
    @RequestMapping(method= RequestMethod.POST , value="/bladevisuals/put-file")
    public ResponseEntity<ResponseWrapper<Map<String,Object>>> putFile(@RequestParam("file") MultipartFile file) {

        ResponseWrapper<Map<String,Object>> responseWrapper = new ResponseWrapper<>();
        responseWrapper.setSuccess(true);

        String filename = file.getOriginalFilename(); //获取上传文件原来的名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());
        String filePath = FILE_PATH + "/upload/" + currentDate + "/";
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }

        File localFile = new File(filePath+filename);
        try {
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename()+" 上传成功");
        }catch (IOException e){
            e.printStackTrace();
        }

        return ResponseEntity.status(HttpStatus.OK)
                .body(responseWrapper);
    }

}

